<?php
declare (strict_types=1);
namespace app\api\middleware;
use auth\Auths;
use app\models\User as UserModel;

/**
 * 登录校验中间件
 * @package app\middleware
 */
class CheckLogin
{
    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
    	$tokens = [];
    	$token = $request->header('x-token');
        $annotation = \base\other\Actions::getMethodDesc();
		
		//验证请求方法
		$method = strtolower($annotation['method'] ?? 'all');
		if( $method !='all' && strtolower($request->method()) != $method ){
			return \Api::ReError('请求错误！');
		}

       	//没登录 - 则直接返回登录页
		if( $annotation['global login'] != 'false' ){
			if(!$token){
				return \Api::ReError('请登录！',-10);
			}
			if( !$tokens = Auths::instance('api')->getTokenInfo($token) ){
				return \Api::ReError('token异常，请重新登录！',-101);
			}
		}
				
		//获取用户基本信息
		if($tokens){
			$request->userInfo = $userInfo =  $tokens['info'];
			$request->userId = $userInfo['id'] ?? 0;
			if(!$request->userInfo){
				return \Api::ReError('token异常，请重新登录！',-10);
			}
		}
		
		//返回
		return $next($request);
    }
}
